﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace CharacterIdUpdater
{
    class Program
    {
        static void Main(string[] args)
        {
            Update();
        }

        static void Update()
        {
            var names = GetNames();
            if(!names.Any()) return;

            int count =0;

            using (var cnn = new SqlConnection(@"data source=(local)\sql2008;initial catalog=ekb;Integrated Security=SSPI;"))
            using (var cmd = cnn.CreateCommand())
            using(var evesvc = new EveKillboard.Core.Services.EveApiServicesProvider())
            {
                cnn.Open();
                
                foreach (var name in names)
                {
                    var charId = evesvc.GetCharacterId(name);
                    if (!charId.HasValue) continue;

                    Console.WriteLine("Updating Character " + name);

                    cmd.CommandText = string.Format("Update Characters Set CharacterID = {0} where Name='{1}'",charId.Value, name.Replace("'","''"));
                    try
                    {
                        count += cmd.ExecuteNonQuery();
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("Update of character \"{0}\" has thrown an exception of type {1}. Details: {2}", name, exp.GetType(), exp.Message);
                    }
                }
            }

            Console.WriteLine("{0} Character(s) updated",count);
        }

        static IEnumerable<string> GetNames()
        {
            var list = new List<string>();

            using (var cnn = new SqlConnection(@"data source=(local)\sql2008;initial catalog=ekb;Integrated Security=SSPI;"))
            using(var cmd = cnn.CreateCommand())
            {
                cnn.Open();
                cmd.CommandText = "select Name from Characters where IsNpc = 0 and IsStructure = 0 and ISNUll(CharacterID,0) = 0";
                using(var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add( reader.GetString(0) );
                    }
                }
            }

            return list.ToArray();
        }
    }
}
